from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser,DjangoModelPermissions
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from ..serializers.skus import SKUSerializer, GoodsCategorySerialzier, SPUSpecificationSerialzier
from ..utils import PageNum
from goods.models import SKU, GoodsCategory, SPU


class SKUView(ModelViewSet):
    """
        sku表的增删改查
    """
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定权限
    permission_classes = [IsAdminUser,DjangoModelPermissions]
    # 指定分页器
    pagination_class = PageNum

    def get_queryset(self):
        # 默认返回
        # return self.queryset
        # 对前端传递keyword判断返回不同的查询集数据
        # 1、获取keyword数据
        keyword = self.request.query_params.get('keyword')
        # 2、判断keyword
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    # 获取三级分类信息
    @action(methods=['get'], detail=False)
    def categories(self, request):
        # 1、查询分类表获取三级分类subs 查询下一级的字段
        data = GoodsCategory.objects.filter(subs=None)
        # 2、返回三级分类数据
        ser = GoodsCategorySerialzier(data, many=True)
        return Response(ser.data)

    # 获取商品规格

    def specs(self,request,pk):
        """

        :param request:
        :param pk: spu商品id
        :return:
        """

        # 1、根据id查询spu对象
        spu = SPU.objects.get(id=pk)
        # 2、通过spu对象关联查询规格信息
        spuspecification=spu.specs.all()
        # 3、序列化返回规格信息
        ser=SPUSpecificationSerialzier(spuspecification,many=True)

        return Response(ser.data)


